/*
 * This file is part of aion-emu <aion-emu.com>.
 *
 *  aion-emu is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  aion-emu is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with aion-emu.  If not, see <http://www.gnu.org/licenses/>.
 */
package com.aionemu.gameserver.model.gameobjects;

import java.util.List;

import javolution.util.FastList;

import com.aionemu.gameserver.ai.CtrlEvent;
import com.aionemu.gameserver.controllers.effect.EffectController;
import com.aionemu.gameserver.dataholders.DataManager;
import com.aionemu.gameserver.model.gameobjects.interfaces.IDialogRequest;
import com.aionemu.gameserver.model.gameobjects.interfaces.IDialogSelect;
import com.aionemu.gameserver.model.gameobjects.interfaces.IReward;
import com.aionemu.gameserver.model.gameobjects.interfaces.ISummoned;
import com.aionemu.gameserver.model.gameobjects.knownList.AgressivNPCKnownList;
import com.aionemu.gameserver.model.gameobjects.player.Player;
import com.aionemu.gameserver.model.gameobjects.state.CreatureState;
import com.aionemu.gameserver.model.gameobjects.stats.NpcGameStats;
import com.aionemu.gameserver.model.gameobjects.stats.NpcLifeStats;
import com.aionemu.gameserver.model.team.interfaces.ITeamMember;
import com.aionemu.gameserver.model.templates.npcTemplate.BoundRadius;
import com.aionemu.gameserver.model.templates.npcTemplate.CreatureTemplate;
import com.aionemu.gameserver.model.templates.npcskill.NpcSkillList;
import com.aionemu.gameserver.model.templates.spawn.SpawnTemplate;
import com.aionemu.gameserver.network.aion.serverpackets.SM_DIALOG_WINDOW;
import com.aionemu.gameserver.network.aion.serverpackets.SM_ATTACK_STATUS.TYPE;
import com.aionemu.gameserver.questEngine.QuestEngine;
import com.aionemu.gameserver.questEngine.model.QuestEnv;
import com.aionemu.gameserver.services.DialogService;
import com.aionemu.gameserver.taskmanager.tasks.DecayTaskManager;
import com.aionemu.gameserver.utils.MathUtil;
import com.aionemu.gameserver.utils.PacketSendUtility;

/**
 * This class is a base class for all in-game NPCs, what includes: monsters and npcs that player can talk to (aka
 * Citizens)
 * 
 * @author Luno
 * 
 */
public class Npc extends Creature implements IDialogSelect, IDialogRequest, IReward
{
	private NpcSkillList	npcSkillList;

	/**
	 * Constructor creating instance of Npc.
	 * 
	 * @param spawn
	 *            SpawnTemplate which is used to spawn this npc
	 * @param objId
	 *            unique objId
	 */
	public Npc(int objId, SpawnTemplate spawnTemplate)
	{
		super(objId, spawnTemplate);
		super.setEffectController(new EffectController(this));
		if (DataManager.TRIBE_RELATIONS_DATA.hasAggressiveRelations(getTribe()))
			setKnownlist(new AgressivNPCKnownList(this));
		super.setGameStats(new NpcGameStats(this));
		super.setLifeStats(new NpcLifeStats(this));
	}

	/**
	 * @return the lifeStats
	 */
	@Override
	public NpcLifeStats getLifeStats()
	{
		return (NpcLifeStats) super.getLifeStats();
	}

	/**
	 * @return the gameStats
	 */
	@Override
	public NpcGameStats getGameStats()
	{
		return (NpcGameStats) super.getGameStats();
	}

	public boolean hasWalkRoutes()
	{
		return false;
	}

	@Override
	public void initializeAi()
	{
	}

	/**
	 *  Check whether npc located at initial spawn location
	 *  
	 * @return true or false
	 */
	public boolean isAtSpawnLocation()
	{
		return MathUtil.getDistance(getSpawn().getX(), getSpawn().getY(), getSpawn().getZ(), getX(), getY(), getZ()) < 1;
	}

	/**
	 * @return the npcSkillList
	 */
	public NpcSkillList getNpcSkillList()
	{
		return npcSkillList;
	}

	/**
	 * @param npcSkillList the npcSkillList to set
	 */
	public void setNpcSkillList(NpcSkillList npcSkillList)
	{
		this.npcSkillList = npcSkillList;
	}

	@Override
	public CreatureTemplate getObjectTemplate()
	{
		return (CreatureTemplate) super.getObjectTemplate();
	}

	@Override
	public boolean canSee(Creature player)
	{
		if (!player.isInState(CreatureState.COMBAT))
			return false;

		switch (getObjectTemplate().getCommonData().getRating())
		{
			case JUNK:
			case NORMAL:
				if (player.getVisualState() < 1)
					return true;
				break;
			case ELITE:
				if (player.getVisualState() < 2)
					return true;
				break;
			default:
				return player.getVisualState() < 2;
		}
		return false;
	}

	@Override
	public void onRespawn()
	{
		super.onRespawn();

		//set state from npc templates
		if (getObjectTemplate().getState() != 0)
			setState(getObjectTemplate().getState());
		else
			setState(65);

		getLifeStats().setCurrentHpPercent(100);
	}

	@Override
	public void doReward()
	{
		AionObject winner = getAggroList().getMostDamage();

		if (winner == null)
			return;
		if (winner instanceof ITeamMember)
			((ITeamMember) winner).getReward(this);
	}

	@Override
	public void onDialogRequest(Player player)
	{
		if (QuestEngine.getInstance().onDialog(new QuestEnv(this, player, 0, -1)))
			return;
		// TODO need check here
		PacketSendUtility.sendPacket(player, new SM_DIALOG_WINDOW(getObjectId(), 10));
	}

	/**
	 * Handle dialog
	 */
	@Override
	public boolean onDialogSelect(int dialogId, final Player player, int questId)
	{
		DialogService.onDialogSelect(dialogId, player, this, questId);
		return true;
	}

	@Override
	public void onAttack(Creature creature, int skillId, TYPE type, int damage)
	{
		if (creature instanceof ISummoned)
			creature = ((ISummoned) creature).getMaster();

		super.onAttack(creature, skillId, type, damage);

		if (creature instanceof Player)
			if (QuestEngine.getInstance().onAttack(new QuestEnv(this, (Player) creature, 0, 0)))
				return;

		for (Npc sup : getSupportsInRange(10))
			//FIXME see aggro, trap make hate?
			sup.getAggroList().addHate(creature, 10);
	}

	public List<Npc> getSupportsInRange(float range)
	{
		List<Npc> list = new FastList<Npc>();

		for (VisibleObject obj : getKnownList().getKnownObjects().values())
		{
			if (obj instanceof Npc)
			{
				Npc tmp = (Npc) obj;
				if (isSupportTo(tmp) && MathUtil.isInRange(this, obj, range))
				{
					list.add(tmp);

				}
			}
		}
		return list;
	}

	public BoundRadius getBoundingRadius()
	{
		return getObjectTemplate().getBoundRadius();
	}
	/* (non-Javadoc)
	 * @see com.aionemu.gameserver.model.gameobjects.Creature#onDie(com.aionemu.gameserver.model.gameobjects.Creature)
	 */
	@Override
	public void onDie(Creature lastAttacker)
	{
		if (hasAI())
			getAI().notifyEvent(CtrlEvent.EVT_DEAD, null);
		DecayTaskManager.getInstance().addDecayTask(this);
		scheduleRespawn();
		super.onDie(lastAttacker);
	}
}
